import * as emitter from "@/libs/emitter";
import type { UserSex, User } from "@/type";

export const useUserStore = defineStore('user', () => {

    const uid = useCookie('UserId', { maxAge: 60 * 60 * 24 * 7 })
    const nickname = ref<string>()
    const sex = ref<UserSex>()
    const avatarUrl = ref<string>()
    const accessToken = useCookie('UserAccessToken', { maxAge: 60 * 60 * 24 * 7 })
    const isLogin = computed(() => !!accessToken.value)

    /**
     * 设置token
     */
    function setAccessToken(val: string) {
        accessToken.value = val
    }

    /**
     *  设置用户信息
     * @param info 用户信息
     */
    function setUserInfo(info: Omit<User, 'password'>) {
        uid.value = info.id.toString()
        nickname.value = info.nickname
        sex.value = info.sex
        avatarUrl.value = info.avatar_url
    }

    /**
     * 退出账号
     */
    function logOut() {
        accessToken.value = ''
        console.log('退出账号');
        // const route = useRoute()
        // navigateTo(route)
        emitter.emit('app_logout_leave')
    }
    return {
        uid,
        nickname,
        sex,
        accessToken,
        avatarUrl,
        isLogin,
        setUserInfo,
        setAccessToken,
        logOut
    }
}, {
    persist: {
        paths: ['uid', 'nickname', 'sex', 'avatarUrl']
    }
})
